import { Scalar, CustomScalar } from '@nestjs/graphql';
import { Kind, ValueNode } from 'graphql';
import * as moment from 'moment';

@Scalar('Date', type => Date)
export class DateScalar implements CustomScalar<string, Date> {
  description = 'Date custom scalar type';

  parseValue(value: string) {
    return new Date(value); // value from the client
  }

  serialize(value): string {
    return moment(value).format('YYYY-MM-DD HH:mm:ss'); // value sent to the client
  }

  parseLiteral(ast: ValueNode) {
    if (ast.kind === Kind.INT) {
      return new Date(ast.value); // ast value is always in string format
    }
    return null;
  }
}
